//
//  HJHttpTool.m
//  project
//
//  Created by hu on 2019/3/20.
//  Copyright © 2019 hu. All rights reserved.
//

#import "HJHttpTool.h"
#import "AFNetworking.h"
#import "NSString+HJDeviceRegister.h"
#import "HJPerfectInfomationVC.h"
//默认刷新token尝试次数
#define RefreshTokenRetryCount 3

@implementation HJHttpTool

+(void)get:(NSString *)url params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure {
    // 1.创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval = 20;
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    [mgr.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [mgr.requestSerializer setValue:[self token] forHTTPHeaderField:@"Authorization"];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    LKLog(@"url=%@, params=%@",url,[self getNewParamsFromParams:params]);
    [mgr GET:url parameters:[self getNewParamsFromParams:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //判断接口是否成功返回
        NSError * parseError1 = nil;
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&parseError1];
        if (parseError1) {
            NSLog(@"JSON解析错误");
            return;
        }
        HJResponeds *respond = [[HJResponeds alloc] init];
        if ([dic[@"code"] integerValue] == 200) {
            respond.isSuccess = YES;
            respond.data = dic[@"data"];
            respond.resultDesc = dic[@"msg"];
            if (success) {
                success(respond);
            }
        } else {
            respond.isSuccess = NO;
            respond.data = nil;
            respond.resultDesc = dic[@"msg"];
            if (failure) {
                failure(respond.resultDesc);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
        //通讯协议状态码
        if (response.statusCode == 401) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                @weakify(self)
                [self refreshTokenWithSuccess:^(BOOL isYes) {
                    @strongify(self)
                    if (isYes) {
                        [self get:url params:[self getNewParamsFromParams:params] success:success failure:failure];
                    }else {
                        [mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
                    }
                }];
                return;
            });
        } else {
            if (failure) {
                failure(error.localizedDescription);
            }
        }
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    }];
}
+ (void)post:(NSString *)url params:(NSDictionary *)params success:(SuccessBlock)success failure:(FailureBlock)failure {
  // 1.创建请求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.requestSerializer.timeoutInterval = 20;
    mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mgr.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [mgr.requestSerializer setValue:[self token] forHTTPHeaderField:@"Authorization"];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
   //  2.发送请求
    LKLog(@"url=%@, params=%@",url,[self getNewParamsFromParams:params]);
    
    [mgr POST:url parameters:[self getNewParamsFromParams:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //判断接口是否成功返回
        NSError * parseError1 = nil;
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&parseError1];
        if (parseError1) {
            NSLog(@"JSON解析错误");
            return;
        }
        // LKLog(@"服务器返回数据：%@", dic);
        HJResponeds *respond = [[HJResponeds alloc] init];
        respond.code = [dic[@"code"] integerValue];
        if (respond.code == 200) {
            respond.isSuccess = YES;
            respond.data = dic[@"data"];
            respond.resultDesc = dic[@"msg"];
            if (success) {
                success(respond);
            }
        }else if (respond.code == 1103 || respond.code == 1106) {
            respond.    isSuccess = NO;
            respond.data = dic[@"data"];
            if (success) {
                success(respond);
            }
        } else {
            respond.isSuccess = NO;
            respond.data = nil;
//            if (DEBUG) {
//                if (failure) {
//                    failure(dic[@"error"]);
//                }
//            }else {
                respond.resultDesc = dic[@"msg"];
                if (failure) {
                    failure(respond.resultDesc);
                }
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
        //通讯协议状态码
        if (response.statusCode == 401) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                @weakify(self)
                [self refreshTokenWithSuccess:^(BOOL isYes) {
                    @strongify(self)
                    if (isYes) {
                        @strongify(self)
                        [self post:url params:[self getNewParamsFromParams:params] success:success failure:failure];
                    }else {
                        [mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
                    }
                }];
                return;
            });
        } else {
            if (failure) {
                failure(error.localizedDescription);
            }
        }
        //服务器返回的业务逻辑报文信息
//        NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
//        NSData * data = [errResponse dataUsingEncoding:NSUTF8StringEncoding];
//        NSDictionary *tempDictQueryDiamond = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//        failure(task,error);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
}
#pragma mark --Body POST 请求
+ (void)postWithUrl:(NSString *)url body:(NSData *)body success:(SuccessBlock)success failure:(FailureBlock)failure {
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    request.timeoutInterval = 10;
    [request setHTTPBody:body];
    [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [request setValue:[self token] forHTTPHeaderField:@"Authorization"];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"application/x-www-form-urlencoded;charset=UTF-8", nil];
    manager.responseSerializer = responseSerializer;
   
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){
         [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        if(responseObject!=nil){
            //判断接口是否成功返回
            NSError * parseError1 = nil;
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&parseError1];
            if (parseError1) {
                NSLog(@"JSON解析错误");
                return;
            }
            HJResponeds *respond = [[HJResponeds alloc] init];
            if ([dic[@"code"] integerValue] == 200) {
                respond.isSuccess = YES;
                respond.data = dic[@"data"];
                respond.resultDesc = dic[@"msg"];
                if (success) {
                    success(respond);
                }
            } else {
                respond.isSuccess = NO;
                respond.data = nil;
                respond.resultDesc = dic[@"msg"];
                if (failure) {
                    failure(respond.resultDesc);
                }
            }
            respond.code = [dic[@"code"] integerValue];
        }if (error) {
            failure(error.localizedDescription);
        }}]resume];
}

/// 上传图片
+ (void)uploadImageWithUrl:(NSString *)url params:(NSDictionary *)params name:(NSString *)name imageArray:(NSArray *)imageArray completion:(void (^)(NSArray *result, NSError *error))completion {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFHTTPRequestSerializer * requestSeri = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [requestSeri setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    [requestSeri setValue:[self token] forHTTPHeaderField:@"Authorization"];
    manager.requestSerializer = requestSeri;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"multipart/form-data", nil];
    [manager POST:url parameters:[self getNewParamsFromParams:params] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i=0; i<imageArray.count; i++) {
            UIImage *image =[imageArray objectAtIndex:i];
            NSData *fileData = UIImageJPEGRepresentation(image, 0.1);
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
            
            if (fileData != NULL) {
                [formData appendPartWithFileData:fileData name:name fileName:fileName mimeType:@"image/png"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"%lld",uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (completion) {
            id res = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            completion(res[@"data"], nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = (NSHTTPURLResponse*)task.response;
        //通讯协议状态码
        if (response.statusCode == 401) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                @weakify(self)
                [self refreshTokenWithSuccess:^(BOOL isYes) {
                    @strongify(self)
                    if (isYes) {
                        @strongify(self)
                        [self uploadImageWithUrl:url params:[self getNewParamsFromParams:params] name:name imageArray:imageArray completion:completion];
                    }else {
                        [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
                    }
                }];
                return;
            });
        } else {
            if (completion) {
                completion(nil, error);
            }
        }
        
    }];
}
+ (void)download:(NSString *)url process:(void (^)(NSInteger writedBytes, NSInteger totalBytes))process success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *msg))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    [manager.requestSerializer setValue:[self token] forHTTPHeaderField:@"Authorization"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        process(downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"下载成功");
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"下载失败");
        if (failure)
        {
            failure(error.localizedDescription);
        }
    }];
}
+ (void)UploadFile:(NSString *)url filePath:(NSURL *)filePath name:(NSString *)name param:(NSDictionary *)param process:(void (^)(NSInteger writedBytes, NSInteger totalBytes))process success:(void (^)(NSDictionary *result))success failure:(void (^)(NSString *msg))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:[self token] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil] ;
    [manager POST:url parameters:[self getNewParamsFromParams:param] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileURL:filePath name:@"multipartFile" fileName:name mimeType:@"video/mp4" error:nil];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (process) {
            process(uploadProgress.completedUnitCount, uploadProgress.totalUnitCount);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {
            failure(error.localizedDescription);
        }
    }];
}
#pragma mark - 私有方法
/// 加入公共参数
+ (NSDictionary *)getNewParamsFromParams:(NSDictionary *)params {
    NSMutableDictionary *newParams = [[NSMutableDictionary alloc] initWithDictionary:params];
    [newParams addEntriesFromDictionary:[self getEncrypt]];
    return newParams;
}

+(NSDictionary *)getEncrypt {
    // 接口版本号
    NSInteger apiVersion = 1.0;
    // appversion
    NSString * appVersion =[CommonTools appVersion];
    //当前访问设备
    NSString * deviceCode = [NSString getUUIDByKeyChain];
    // 渠道来源
    NSString * source = @"appStore";
    // 时间戳
    NSString * time = [NSDate timestamp];
    NSDictionary * dic = @{@"apiv":@(apiVersion),
                           @"appv":appVersion,
                           @"deviceCode":deviceCode,
                           @"source":source,
                           @"time":time};
    return dic;
}

//+ (AFHTTPSessionManager *)sharedManager {
//    static AFHTTPSessionManager *manager = nil;
//    static dispatch_once_t predicate;
//    dispatch_once(&predicate, ^{
//        manager = [AFHTTPSessionManager manager];
//        manager.operationQueue.maxConcurrentOperationCount = 5;
//        manager.requestSerializer.timeoutInterval= 30.f;
//        manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        [manager.requestSerializer setValue:[self token] forHTTPHeaderField:@"Authorization"];
//    });
//    return manager;
//}

/*** 将1请求参数转为字符串 */
//+ (NSString *)keyValueStringWithParams:(NSDictionary *)params {
//    NSDictionary * dict = [self getNewParamsFromParams:params];
//    if (dict == nil) {
//        return nil;
//    }
//    NSMutableString *string = [NSMutableString stringWithString:@"?"];
//    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
//        [string appendFormat:@"%@=%@&",key,obj];
//    }];
//
//    if ([string rangeOfString:@"&"].length) {
//        [string deleteCharactersInRange:NSMakeRange(string.length - 1, 1)];
//    }
//    return string;
//}

/**
 token 刷新
 */
+(void)refreshTokenWithSuccess:(void(^)(BOOL isYes))success {
    NSString * url = [Api stringByAppendingString:TokenApi];
//    BOOL isLogin = [[mUserDefaults objectForKey:@"isLogin"] isEqualToString:@"1"];
//    if (![self token].length && isLogin) {
//        if (success) {
//            success(NO);
//        }
//        return;
//    }
    [self post:url params:nil success:^(HJResponeds *result) {
        if ([result.data isEqual:[NSNull null]]) {
            if (success) {
                success(NO);
            }
            return;
        }
        [HJUserManager getUserModel].token = result.data;
        [mUserDefaults setObject:result.data forKey:@"token"];
        [mUserDefaults synchronize];
        if (success) {
            success(YES);
        }
    } failure:^(id result) {
        if (success) {
            success(NO);
        }
    }];
}


+(NSString *)token {
    NSString * Authorization = [mUserDefaults objectForKey:@"token"];
    return Authorization;
}
@end


@implementation HJResponeds

- (instancetype)init {
    self = [super init];
    if (self) {
        self.resultDesc = @"服务器出错啦~";
        self.data = nil;
        self.isSuccess = NO;
    }
    return self;
}

- (NSString *)description {
    return [self yy_modelDescription];
}
//-(void)setCode:(NSInteger)code {
//    switch (code) {
//        case 40301:
//
//            break;
//        default:
//            break;
//    }
//}
@end
